<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备配置管理 - 工业物联网数据采集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2c3e50;
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --warning-color: #f39c12;
            --info-color: #3498db;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .card {
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: none;
            backdrop-filter: blur(15px);
            background: rgba(255, 255, 255, 0.95);
        }
        
        .device-card {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        
        .device-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.15);
        }
        
        .device-card.enabled {
            border-left-color: var(--success-color);
        }
        
        .device-card.disabled {
            border-left-color: var(--danger-color);
        }
        
        .protocol-badge {
            border-radius: 20px;
            padding: 4px 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .protocol-modbus { background: linear-gradient(45deg, #4CAF50, #45a049); }
        .protocol-s7 { background: linear-gradient(45deg, #2196F3, #1976D2); }
        .protocol-mqtt { background: linear-gradient(45deg, #FF9800, #F57C00); }
        .protocol-opcua { background: linear-gradient(45deg, #9C27B0, #7B1FA2); }
        
        .form-section {
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            background: #f8f9fa;
        }
        
        .point-item {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            background: white;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        
        .status-online { background-color: var(--success-color); }
        .status-offline { background-color: var(--danger-color); }
        
        .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, var(--primary-color), #34495e);
            color: white;
            border: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), #34495e);
            border: none;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.1);
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: linear-gradient(135deg, var(--primary-color), #34495e);">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-industry me-2"></i>工业物联网数据采集系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="fas fa-home me-1"></i>主控台
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/dashboard">
                            <i class="fas fa-chart-line me-1"></i>监控仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/device-manager">
                            <i class="fas fa-cogs me-1"></i>设备管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/device-config">
                            <i class="fas fa-plus-circle me-1"></i>快速配置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/status-test">
                            <i class="fas fa-stethoscope me-1"></i>系统诊断
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- 操作按钮区 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-list me-2"></i>设备列表</h4>
                            <div>
                                <button class="btn btn-success me-2" onclick="addDevice()">
                                    <i class="fas fa-plus me-1"></i>添加设备
                                </button>
                                <button class="btn btn-primary me-2" onclick="loadDevices()">
                                    <i class="fas fa-sync me-1"></i>刷新
                                </button>
                                <button class="btn btn-info" onclick="importConfig()">
                                    <i class="fas fa-file-import me-1"></i>导入配置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 设备列表 -->
        <div class="row" id="deviceList">
            <!-- 设备卡片将在这里动态生成 -->
        </div>
    </div>

    <!-- 设备配置模态框 -->
    <div class="modal fade" id="deviceModal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-cog me-2"></i><span id="modalTitle">设备配置</span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="deviceForm">
                        <!-- 基本信息 -->
                        <div class="form-section">
                            <h6><i class="fas fa-info-circle me-2"></i>基本信息</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">设备名称*</label>
                                    <input type="text" class="form-control" id="deviceName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">设备描述</label>
                                    <input type="text" class="form-control" id="deviceDescription">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">协议类型*</label>
                                    <select class="form-select" id="deviceType" onchange="updateConfigForm()" required>
                                        <option value="">请选择协议</option>
                                        <option value="modbus">Modbus TCP/RTU</option>
                                        <option value="s7">Siemens S7</option>
                                        <option value="mqtt">MQTT</option>
                                        <option value="opcua">OPC UA</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">采集间隔(ms)*</label>
                                    <input type="number" class="form-control" id="pollingInterval" value="1000" min="100" required>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-check mt-3">
                                        <input class="form-check-input" type="checkbox" id="deviceEnabled" checked>
                                        <label class="form-check-label" for="deviceEnabled">
                                            启用设备
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 协议配置 -->
                        <div class="form-section" id="protocolConfig">
                            <h6><i class="fas fa-network-wired me-2"></i>协议配置</h6>
                            <div id="protocolFields">
                                <!-- 协议特定字段将在这里动态生成 -->
                            </div>
                        </div>

                        <!-- 数据点配置 -->
                        <div class="form-section">
                            <h6><i class="fas fa-tags me-2"></i>数据点配置</h6>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <span>已配置 <span id="pointCount">0</span> 个数据点</span>
                                <button type="button" class="btn btn-success btn-sm" onclick="addPoint()">
                                    <i class="fas fa-plus me-1"></i>添加数据点
                                </button>
                            </div>
                            <div id="pointsList">
                                <!-- 数据点将在这里动态生成 -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-warning me-2" onclick="testConnection()">
                        <i class="fas fa-plug me-1"></i>测试连接
                    </button>
                    <button type="button" class="btn btn-primary" onclick="saveDevice()">
                        <i class="fas fa-save me-1"></i>保存配置
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 数据点配置模板 -->
    <template id="pointTemplate">
        <div class="point-item">
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">点名*</label>
                    <input type="text" class="form-control point-name" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">描述</label>
                    <input type="text" class="form-control point-description">
                </div>
                <div class="col-md-2">
                    <label class="form-label">数据类型*</label>
                    <select class="form-select point-datatype" required>
                        <option value="bool">Boolean</option>
                        <option value="int16">Int16</option>
                        <option value="int32">Int32</option>
                        <option value="float">Float</option>
                        <option value="string">String</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">访问权限</label>
                    <select class="form-select point-access">
                        <option value="R">只读</option>
                        <option value="W">只写</option>
                        <option value="RW">读写</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <div class="d-flex align-items-end">
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removePoint(this)">
                            <i class="fas fa-trash"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-info ms-1" onclick="togglePointAdvanced(this)">
                            <i class="fas fa-cog"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="point-advanced" style="display: none;">
                <hr class="my-3">
                <div class="row">
                    <div class="col-md-4">
                        <label class="form-label">地址/节点ID*</label>
                        <input type="text" class="form-control point-address" required>
                        <small class="text-muted">如: 40001, DB1.DBD10, ns=2;i=2</small>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">单位</label>
                        <input type="text" class="form-control point-unit">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">MQTT主题 (仅MQTT)</label>
                        <input type="text" class="form-control point-topic">
                    </div>
                </div>
                
                <!-- 报警配置 -->
                <div class="mt-3">
                    <div class="form-check">
                        <input class="form-check-input point-alarm-enabled" type="checkbox" onchange="toggleAlarmConfig(this)">
                        <label class="form-check-label">启用报警</label>
                    </div>
                    <div class="alarm-config mt-2" style="display: none;">
                        <div class="row">
                            <div class="col-md-3">
                                <label class="form-label">报警类型</label>
                                <select class="form-select point-alarm-type">
                                    <option value="threshold">阈值报警</option>
                                    <option value="state_change">状态变化</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">高报警</label>
                                <input type="number" class="form-control point-alarm-high" step="0.01">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">高高报警</label>
                                <input type="number" class="form-control point-alarm-critical" step="0.01">
                            </div>
                            <div class="col-md-5">
                                <label class="form-label">报警消息</label>
                                <input type="text" class="form-control point-alarm-message">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let devices = [];
        let currentDevice = null;
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadDevices();
        });
        
        // 加载设备列表
        async function loadDevices() {
            try {
                const response = await fetch('/api/devices/config');
                if (response.ok) {
                    const data = await response.json();
                    devices = data.devices || [];
                    renderDeviceList();
                } else {
                    // 如果API不存在，加载示例数据
                    devices = getExampleDevices();
                    renderDeviceList();
                }
            } catch (error) {
                console.error('加载设备失败:', error);
                devices = getExampleDevices();
                renderDeviceList();
            }
        }
        
        // 渲染设备列表
        function renderDeviceList() {
            const container = document.getElementById('deviceList');
            container.innerHTML = '';
            
            devices.forEach((device, index) => {
                const card = createDeviceCard(device, index);
                container.appendChild(card);
            });
        }
        
        // 创建设备卡片
        function createDeviceCard(device, index) {
            const col = document.createElement('div');
            col.className = 'col-lg-6 col-xl-4 mb-4';
            
            col.innerHTML = `
                <div class="card device-card ${device.enabled ? 'enabled' : 'disabled'}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <h6 class="card-title mb-1">${device.name}</h6>
                                <p class="text-muted small mb-2">${device.description || '无描述'}</p>
                            </div>
                            <span class="protocol-badge protocol-${device.type} text-white">
                                ${device.type.toUpperCase()}
                            </span>
                        </div>
                        
                        <div class="row text-center mb-3">
                            <div class="col-4">
                                <div class="small text-muted">状态</div>
                                <div>
                                    <span class="status-indicator ${device.enabled ? 'status-online' : 'status-offline'}"></span>
                                    ${device.enabled ? '启用' : '禁用'}
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="small text-muted">数据点</div>
                                <div class="fw-bold">${device.points ? device.points.length : 0}</div>
                            </div>
                            <div class="col-4">
                                <div class="small text-muted">间隔</div>
                                <div class="fw-bold">${device.polling_interval}ms</div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button class="btn btn-sm btn-outline-primary flex-fill" onclick="editDevice(${index})">
                                <i class="fas fa-edit me-1"></i>编辑
                            </button>
                            <button class="btn btn-sm btn-outline-success" onclick="duplicateDevice(${index})">
                                <i class="fas fa-copy me-1"></i>复制
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteDevice(${index})">
                                <i class="fas fa-trash me-1"></i>删除
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            return col;
        }
        
        // 添加设备
        function addDevice() {
            currentDevice = null;
            document.getElementById('modalTitle').textContent = '添加设备';
            document.getElementById('deviceForm').reset();
            document.getElementById('pointsList').innerHTML = '';
            updatePointCount();
            new bootstrap.Modal(document.getElementById('deviceModal')).show();
        }
        
        // 编辑设备
        function editDevice(index) {
            currentDevice = index;
            const device = devices[index];
            document.getElementById('modalTitle').textContent = '编辑设备 - ' + device.name;
            
            // 填充基本信息
            document.getElementById('deviceName').value = device.name;
            document.getElementById('deviceDescription').value = device.description || '';
            document.getElementById('deviceType').value = device.type;
            document.getElementById('pollingInterval').value = device.polling_interval;
            document.getElementById('deviceEnabled').checked = device.enabled;
            
            // 更新协议配置
            updateConfigForm();
            fillProtocolConfig(device.config);
            
            // 填充数据点
            fillPoints(device.points || []);
            
            new bootstrap.Modal(document.getElementById('deviceModal')).show();
        }
        
        // 更新协议配置表单
        function updateConfigForm() {
            const type = document.getElementById('deviceType').value;
            const container = document.getElementById('protocolFields');
            
            let html = '';
            
            switch(type) {
                case 'modbus':
                    html = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">IP地址*</label>
                                <input type="text" class="form-control" id="config_ip" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">端口*</label>
                                <input type="number" class="form-control" id="config_port" value="502" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">单元ID</label>
                                <input type="number" class="form-control" id="config_unit_id" value="1">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">超时(秒)</label>
                                <input type="number" class="form-control" id="config_timeout" value="3">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">重试次数</label>
                                <input type="number" class="form-control" id="config_retries" value="3">
                            </div>
                        </div>
                    `;
                    break;
                case 's7':
                    html = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">IP地址*</label>
                                <input type="text" class="form-control" id="config_ip" required>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">机架号</label>
                                <input type="number" class="form-control" id="config_rack" value="0">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">插槽号</label>
                                <input type="number" class="form-control" id="config_slot" value="1">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">超时(秒)</label>
                                <input type="number" class="form-control" id="config_timeout" value="5">
                            </div>
                        </div>
                    `;
                    break;
                case 'mqtt':
                    html = `
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">Broker地址*</label>
                                <input type="text" class="form-control" id="config_broker" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">端口*</label>
                                <input type="number" class="form-control" id="config_port" value="1883" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" id="config_username">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">密码</label>
                                <input type="password" class="form-control" id="config_password">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">客户端ID</label>
                                <input type="text" class="form-control" id="config_client_id">
                            </div>
                        </div>
                    `;
                    break;
                case 'opcua':
                    html = `
                        <div class="row">
                            <div class="col-md-12">
                                <label class="form-label">端点URL*</label>
                                <input type="text" class="form-control" id="config_endpoint" 
                                       placeholder="opc.tcp://server:4840" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" id="config_username">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">密码</label>
                                <input type="password" class="form-control" id="config_password">
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">安全策略</label>
                                <select class="form-select" id="config_security_policy">
                                    <option value="None">None</option>
                                    <option value="Basic256Sha256">Basic256Sha256</option>
                                    <option value="Aes128_Sha256_RsaOaep">Aes128_Sha256_RsaOaep</option>
                                </select>
                            </div>
                        </div>
                    `;
                    break;
            }
            
            container.innerHTML = html;
        }
        
        // 填充协议配置
        function fillProtocolConfig(config) {
            if (!config) return;
            
            Object.keys(config).forEach(key => {
                const element = document.getElementById('config_' + key);
                if (element) {
                    element.value = config[key];
                }
            });
        }
        
        // 添加数据点
        function addPoint() {
            const template = document.getElementById('pointTemplate');
            const clone = template.content.cloneNode(true);
            document.getElementById('pointsList').appendChild(clone);
            updatePointCount();
        }
        
        // 移除数据点
        function removePoint(button) {
            button.closest('.point-item').remove();
            updatePointCount();
        }
        
        // 切换数据点高级选项
        function togglePointAdvanced(button) {
            const pointItem = button.closest('.point-item');
            const advanced = pointItem.querySelector('.point-advanced');
            const isVisible = advanced.style.display !== 'none';
            
            advanced.style.display = isVisible ? 'none' : 'block';
            button.innerHTML = isVisible ? 
                '<i class="fas fa-cog"></i>' : 
                '<i class="fas fa-times"></i>';
        }
        
        // 切换报警配置
        function toggleAlarmConfig(checkbox) {
            const alarmConfig = checkbox.closest('.point-item').querySelector('.alarm-config');
            alarmConfig.style.display = checkbox.checked ? 'block' : 'none';
        }
        
        // 更新数据点计数
        function updatePointCount() {
            const count = document.querySelectorAll('.point-item').length;
            document.getElementById('pointCount').textContent = count;
        }
        
        // 填充数据点
        function fillPoints(points) {
            document.getElementById('pointsList').innerHTML = '';
            points.forEach(point => {
                addPoint();
                const pointItems = document.querySelectorAll('.point-item');
                const lastPoint = pointItems[pointItems.length - 1];
                
                lastPoint.querySelector('.point-name').value = point.name || '';
                lastPoint.querySelector('.point-description').value = point.description || '';
                lastPoint.querySelector('.point-datatype').value = point.data_type || 'float';
                lastPoint.querySelector('.point-access').value = point.access || 'R';
                lastPoint.querySelector('.point-address').value = point.address || point.node_id || '';
                lastPoint.querySelector('.point-unit').value = point.unit || '';
                lastPoint.querySelector('.point-topic').value = point.topic || '';
                
                if (point.alarm && point.alarm.enabled) {
                    const alarmCheckbox = lastPoint.querySelector('.point-alarm-enabled');
                    alarmCheckbox.checked = true;
                    toggleAlarmConfig(alarmCheckbox);
                    
                    lastPoint.querySelector('.point-alarm-type').value = point.alarm.type || 'threshold';
                    lastPoint.querySelector('.point-alarm-high').value = point.alarm.high || '';
                    lastPoint.querySelector('.point-alarm-critical').value = point.alarm.critical || '';
                    lastPoint.querySelector('.point-alarm-message').value = point.alarm.message || '';
                }
            });
        }
        
        // 保存设备
        async function saveDevice() {
            try {
                // 显示保存中状态
                const saveButton = document.querySelector('.btn-primary[onclick="saveDevice()"]');
                const originalText = saveButton.innerHTML;
                saveButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>保存中...';
                saveButton.disabled = true;
                
                const deviceData = collectFormData();
                
                // 验证必填字段
                if (!deviceData.name || !deviceData.type) {
                    throw new Error('设备名称和协议类型为必填项');
                }
                
                // 发送保存请求
                const response = await fetch('/api/device/config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(deviceData)
                });
                
                const result = await response.json();
                
                // 恢复按钮状态
                saveButton.innerHTML = originalText;
                saveButton.disabled = false;
                
                if (result.success) {
                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('deviceModal')).hide();
                    
                    // 重新加载设备列表
                    await loadDevices();
                    
                    // 显示成功消息
                    Swal.fire({
                        title: '保存成功',
                        text: result.message,
                        icon: 'success',
                        timer: 2000,
                        timerProgressBar: true,
                        showConfirmButton: false
                    });
                    
                } else {
                    // 显示错误详情
                    let errorMessage = result.error;
                    if (result.details && Array.isArray(result.details)) {
                        errorMessage += '\n详细错误:\n' + result.details.join('\n');
                    }
                    
                    Swal.fire({
                        title: '保存失败',
                        text: errorMessage,
                        icon: 'error',
                        confirmButtonText: '确定'
                    });
                }
                
            } catch (error) {
                console.error('保存设备失败:', error);
                
                // 恢复按钮状态
                const saveButton = document.querySelector('.btn-primary[onclick="saveDevice()"]');
                saveButton.innerHTML = '<i class="fas fa-save me-1"></i>保存配置';
                saveButton.disabled = false;
                
                Swal.fire({
                    title: '保存失败',
                    text: error.message || '网络连接失败，请检查服务器状态',
                    icon: 'error',
                    confirmButtonText: '确定'
                });
            }
        }
        
        // 收集表单数据
        function collectFormData() {
            const type = document.getElementById('deviceType').value;
            
            // 基本信息
            const device = {
                name: document.getElementById('deviceName').value,
                description: document.getElementById('deviceDescription').value,
                type: type,
                enabled: document.getElementById('deviceEnabled').checked,
                polling_interval: parseInt(document.getElementById('pollingInterval').value),
                config: {},
                points: []
            };
            
            // 协议配置
            const configFields = document.querySelectorAll('#protocolFields input, #protocolFields select');
            configFields.forEach(field => {
                const key = field.id.replace('config_', '');
                if (field.value) {
                    device.config[key] = field.type === 'number' ? 
                        parseFloat(field.value) : field.value;
                }
            });
            
            // 数据点配置
            const pointItems = document.querySelectorAll('.point-item');
            pointItems.forEach(item => {
                const point = {
                    name: item.querySelector('.point-name').value,
                    description: item.querySelector('.point-description').value,
                    data_type: item.querySelector('.point-datatype').value,
                    access: item.querySelector('.point-access').value,
                    unit: item.querySelector('.point-unit').value
                };
                
                // 地址/节点ID
                const address = item.querySelector('.point-address').value;
                if (type === 'opcua') {
                    point.node_id = address;
                } else if (type === 'mqtt') {
                    point.topic = item.querySelector('.point-topic').value;
                } else {
                    point.address = address;
                }
                
                // 报警配置
                if (item.querySelector('.point-alarm-enabled').checked) {
                    point.alarm = {
                        enabled: true,
                        type: item.querySelector('.point-alarm-type').value,
                        high: parseFloat(item.querySelector('.point-alarm-high').value) || null,
                        critical: parseFloat(item.querySelector('.point-alarm-critical').value) || null,
                        message: item.querySelector('.point-alarm-message').value
                    };
                }
                
                device.points.push(point);
            });
            
            return device;
        }
        
        // 测试连接
        async function testConnection() {
            try {
                // 显示测试中状态
                const testButton = document.querySelector('.btn-warning[onclick="testConnection()"]');
                const originalText = testButton.innerHTML;
                testButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>测试中...';
                testButton.disabled = true;
                
                const deviceData = collectFormData();
                
                // 验证必要的连接参数
                if (!deviceData.name || !deviceData.type) {
                    throw new Error('请填写设备名称和协议类型');
                }
                
                if (!deviceData.config || Object.keys(deviceData.config).length === 0) {
                    throw new Error('请完善协议配置参数');
                }
                
                // 发送测试请求
                const response = await fetch('/api/device/test-connection', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(deviceData)
                });
                
                const result = await response.json();
                
                // 恢复按钮状态
                testButton.innerHTML = originalText;
                testButton.disabled = false;
                
                if (result.success) {
                    Swal.fire({
                        title: '连接成功',
                        html: `
                            <div class="text-start">
                                <p class="mb-2"><strong>设备:</strong> ${deviceData.name}</p>
                                <p class="mb-2"><strong>协议:</strong> ${deviceData.type.toUpperCase()}</p>
                                <p class="mb-2"><strong>状态:</strong> <span class="text-success">在线</span></p>
                                ${result.connection_time ? `<p class="mb-0"><strong>响应时间:</strong> ${result.connection_time}</p>` : ''}
                            </div>
                        `,
                        icon: 'success',
                        confirmButtonText: '确定'
                    });
                } else {
                    Swal.fire({
                        title: '连接失败',
                        html: `
                            <div class="text-start">
                                <p class="mb-2"><strong>设备:</strong> ${deviceData.name}</p>
                                <p class="mb-2"><strong>协议:</strong> ${deviceData.type.toUpperCase()}</p>
                                <p class="mb-2"><strong>错误:</strong> <span class="text-danger">${result.error}</span></p>
                                <hr>
                                <small class="text-muted">
                                    请检查:
                                    <ul class="mt-2 mb-0">
                                        <li>网络连接是否正常</li>
                                        <li>设备IP地址和端口是否正确</li>
                                        <li>设备是否已启动并支持该协议</li>
                                        <li>防火墙设置是否允许连接</li>
                                    </ul>
                                </small>
                            </div>
                        `,
                        icon: 'error',
                        confirmButtonText: '确定',
                        width: '500px'
                    });
                }
            } catch (error) {
                console.error('测试连接失败:', error);
                
                // 恢复按钮状态
                const testButton = document.querySelector('.btn-warning[onclick="testConnection()"]');
                testButton.innerHTML = '<i class="fas fa-plug me-1"></i>测试连接';
                testButton.disabled = false;
                
                Swal.fire({
                    title: '测试失败',
                    text: error.message || '网络连接失败，请检查服务器状态',
                    icon: 'error',
                    confirmButtonText: '确定'
                });
            }
        }
        
        // 复制设备
        function duplicateDevice(index) {
            const device = JSON.parse(JSON.stringify(devices[index]));
            device.name = device.name + '_copy';
            device.enabled = false;
            devices.push(device);
            renderDeviceList();
        }
        
        // 删除设备
        async function deleteDevice(index) {
            const device = devices[index];
            if (!device) {
                return;
            }
            
            const result = await Swal.fire({
                title: '确认删除',
                text: `确定要删除设备 "${device.name}" 吗？此操作不可恢复！`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                confirmButtonColor: '#dc3545',
                reverseButtons: true
            });
            
            if (result.isConfirmed) {
                try {
                    // 显示删除中状态
                    Swal.fire({
                        title: '删除中...',
                        text: '正在删除设备配置',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // 发送删除请求
                    const response = await fetch(`/api/device/${encodeURIComponent(device.name)}/delete`, {
                        method: 'DELETE'
                    });
                    
                    const deleteResult = await response.json();
                    
                    if (deleteResult.success) {
                        // 从本地数组中移除
                        devices.splice(index, 1);
                        renderDeviceList();
                        
                        // 显示成功消息
                        Swal.fire({
                            title: '删除成功',
                            text: deleteResult.message,
                            icon: 'success',
                            timer: 2000,
                            timerProgressBar: true,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            title: '删除失败',
                            text: deleteResult.error,
                            icon: 'error',
                            confirmButtonText: '确定'
                        });
                    }
                    
                } catch (error) {
                    console.error('删除设备失败:', error);
                    Swal.fire({
                        title: '删除失败',
                        text: '网络连接失败，请检查服务器状态',
                        icon: 'error',
                        confirmButtonText: '确定'
                    });
                }
            }
        }
        
        // 导入配置
        function importConfig() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = async function(e) {
                const file = e.target.files[0];
                if (file) {
                    try {
                        // 显示导入中状态
                        Swal.fire({
                            title: '导入中...',
                            text: '正在读取和验证配置文件',
                            icon: 'info',
                            allowOutsideClick: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        
                        const reader = new FileReader();
                        reader.onload = async function(e) {
                            try {
                                const config = JSON.parse(e.target.result);
                                let importDevices = [];
                                
                                // 支持不同格式的配置文件
                                if (config.devices && Array.isArray(config.devices)) {
                                    importDevices = config.devices;
                                } else if (Array.isArray(config)) {
                                    importDevices = config;
                                } else {
                                    throw new Error('配置文件格式不正确，应包含devices数组');
                                }
                                
                                if (importDevices.length === 0) {
                                    throw new Error('配置文件中没有找到设备配置');
                                }
                                
                                // 询问导入方式
                                const importResult = await Swal.fire({
                                    title: '确认导入',
                                    html: `
                                        <div class="text-start">
                                            <p>找到 <strong>${importDevices.length}</strong> 个设备配置:</p>
                                            <ul class="mb-3">
                                                ${importDevices.slice(0, 5).map(device => 
                                                    `<li>${device.name || '未命名设备'} (${device.type || '未知协议'})</li>`
                                                ).join('')}
                                                ${importDevices.length > 5 ? `<li>...还有 ${importDevices.length - 5} 个设备</li>` : ''}
                                            </ul>
                                            <p>请选择导入方式:</p>
                                        </div>
                                    `,
                                    icon: 'question',
                                    showCancelButton: true,
                                    confirmButtonText: '替换所有设备',
                                    cancelButtonText: '取消',
                                    showDenyButton: true,
                                    denyButtonText: '追加到现有设备',
                                    confirmButtonColor: '#dc3545',
                                    denyButtonColor: '#28a745'
                                });
                                
                                if (importResult.isConfirmed || importResult.isDenied) {
                                    Swal.fire({
                                        title: '保存中...',
                                        text: '正在保存设备配置',
                                        icon: 'info',
                                        allowOutsideClick: false,
                                        showConfirmButton: false,
                                        didOpen: () => {
                                            Swal.showLoading();
                                        }
                                    });
                                    
                                    let finalDevices = [];
                                    if (importResult.isConfirmed) {
                                        // 替换所有设备
                                        finalDevices = importDevices;
                                    } else {
                                        // 追加到现有设备
                                        finalDevices = [...devices, ...importDevices];
                                    }
                                    
                                    // 发送保存请求
                                    const response = await fetch('/api/devices/config', {
                                        method: 'POST',
                                        headers: { 'Content-Type': 'application/json' },
                                        body: JSON.stringify({ devices: finalDevices })
                                    });
                                    
                                    const saveResult = await response.json();
                                    
                                    if (saveResult.success) {
                                        // 重新加载设备列表
                                        await loadDevices();
                                        
                                        Swal.fire({
                                            title: '导入成功',
                                            text: saveResult.message,
                                            icon: 'success',
                                            timer: 3000,
                                            timerProgressBar: true
                                        });
                                    } else {
                                        throw new Error(saveResult.error);
                                    }
                                }
                                
                            } catch (error) {
                                console.error('导入配置失败:', error);
                                Swal.fire({
                                    title: '导入失败',
                                    text: error.message || '配置文件格式错误',
                                    icon: 'error',
                                    confirmButtonText: '确定'
                                });
                            }
                        };
                        
                        reader.readAsText(file);
                        
                    } catch (error) {
                        console.error('读取文件失败:', error);
                        Swal.fire({
                            title: '文件读取失败',
                            text: '无法读取选择的文件',
                            icon: 'error',
                            confirmButtonText: '确定'
                        });
                    }
                }
            };
            input.click();
        }
        
        // 获取示例设备数据
        function getExampleDevices() {
            return [
                {
                    name: "PLC-001",
                    description: "生产线1号PLC",
                    type: "modbus",
                    enabled: true,
                    polling_interval: 1000,
                    config: {
                        ip: "192.168.1.100",
                        port: 502,
                        unit_id: 1,
                        timeout: 3,
                        retries: 3
                    },
                    points: [
                        {
                            name: "motor_speed",
                            description: "电机转速",
                            address: "40001",
                            data_type: "int16",
                            access: "R",
                            unit: "rpm"
                        }
                    ]
                }
            ];
        }
    </script>
</body>
</html> 